import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import moment from "moment";
import { Row, Col, Card, Icon, Button, message, Divider, Form, Input, DatePicker, Table} from "antd";
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from '../Pbulic.less';

const FormItem = Form.Item;
const { MonthPicker } = DatePicker;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ statistics,loading }) => ({
  resdata: statistics.resdata,
  loading: loading.models.statistics,
}))
@Form.create()
export default class ListTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      formValues: {
        createTime: moment().subtract(1, 'months').format("YYYY-MM")
      },
    };
  }

  componentWillUnmount(){
    const { dispatch } = this.props;
    dispatch({
      type: `statistics/appendClearState`,
    })
  }

  componentDidMount() {
    const { pageSize } = this.state;
    const { location, dispatch} = this.props;
    const pagesquery = location.query;

    // 列表
    this.getDataList(pagesquery,pageSize,1);


  }


  // componentWillReceiveProps(nextProps) {
  //   // 外层发起刷新数据请求
  //   if (nextProps.isReloadList === true && this.props.isReloadList === false) {
  //     const { pageSize } = this.state;
  //     this.getDataList({},pageSize,1);
  //     this.props.sotpReloadList();
  //   }
  // }


  getDataList(params,pageSize,currentPage) {
    const { dispatch, match } = this.props;
    dispatch({
      type: 'statistics/fetch_statistics_maintain',
      payload: {
        pageSize,
        currentPage,
        createTime:moment().subtract(1, 'months').format("YYYY-MM"),
        // ...pagesquery,
        ...params,
      },
    });
  }


  // 分页、排序、筛选变化时触发
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      // currentPage: pagination.current,
      // pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.setState({
      currentPage:pagination.current
    },()=>{
      this.getDataList(params,pageSize,pagination.current);
    })

  };

  // 重置表单
  handleFormReset = () => {
    const { form } = this.props;
    const {pageSize,currentPage} = this.state;
    //form.resetFields();
    form.setFieldsValue({
      createTime:moment().subtract(1, 'months'),
    });
    this.setState({
      formValues: {},
    });
    this.getDataList({},pageSize,1);
  };



  // 表单搜索
  handleSearchSubmit = e => {
    e.preventDefault();

    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if(fieldsValue.createTime){
        // fieldsValue.createTime = fieldsValue.createTime.unix() * 1000;
        fieldsValue.createTime = fieldsValue.createTime.format("YYYY-MM");
      }

      this.setState({
        formValues: fieldsValue,
      });

      this.getDataList(fieldsValue,pageSize,1);
    });
  };

  // 导出
  handleExport = () =>{
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'statistics/action_maintain_export',
      payload: {
        ...formValues,
      },
    }).then(()=>{
      message.success("点位养护统计表已导出")
    });
  }


  // 搜索内容
  renderSearchForm() {
    const { form,  location } = this.props;
    const { getFieldDecorator } = form;
    const pagesquery = location.query;

    const monthFormat = 'YYYY/MM';

    return (
      <Form onSubmit={this.handleSearchSubmit} >
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="选择时间">
              {getFieldDecorator('createTime',{
                initialValue: pagesquery && pagesquery.createTime ? pagesquery.createTime : moment().subtract(1, 'months'),
              })(<MonthPicker  format={monthFormat} />)}
            </FormItem>
          </Col>

          <Col md={6} sm={24}>
            <div style={{ float: 'left', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <Button style={{ marginLeft: 8 }}  type="default" onClick={this.handleExport}>
                导出
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }


  render() {

    const { resdata, loading } = this.props;
    const { selectedRows } = this.state;



    const columns = [
      {
        title: "序号",
        dataIndex: 'index',
        align:'center',
        render: (text, row, index)=> (
          <span>{index+1}</span>
        ),
      },
      {
        title: "区域",
        dataIndex: "districtName",
      },
      {
        title: "点位编号",
        dataIndex: "pointCode",
      },
      {
        title: "点位名称",
        dataIndex: "pointName",
      },
      {
        title: "更换或增加设备",
        dataIndex: "changeDev",
      },
      {
        title: "养护结果",
        dataIndex: "repairResult",
      },
      {
        title: "养护日期",
        dataIndex: "lastMaintainTime",
        render: text => (text ? moment(text).format("YYYY-MM-DD HH:mm") : "--")
      },
    ];


    return (
      <PageHeaderLayout>
        <Card bordered={false}  title={"点位养护统计"} headStyle={{textAlign:'center',fontSize:24,fontWeight:800}}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSearchForm()}</div>

            <Table
              rowKey="districtId"
              loading={loading}
              dataSource={resdata.list}
              pagination={resdata.pagination}
              columns={columns}
              onChange={this.handleStandardTableChange}
              bordered
            />

          </div>
        </Card>
      </PageHeaderLayout>

    );
  }
}
